import React, { Component } from 'react'
import styles from './index.module.scss'
import classnames from 'classnames'
import PropTypes from 'prop-types'

export class BackTop extends Component {

    static defaultProps = {
        scrollObj: window
    }
    static propTypes = {
        scrollObj:PropTypes.object
    }

    get pos(){
        const {scrollObj} = this.props

        if(scrollObj == window){
            return {
                right:'.4rem',
                bottom:'2rem'
            }
        }else{
            const {right,bottom} = scrollObj.getBoundingClientRect()
         
            return {
                right:`calc(100vw - ${right}px + 0.4rem)`,
                bottom:`calc(100vh - ${bottom}px + 1rem)`
            }
        }
    }

    constructor(){
        super()

        this.state = {
            isBack: false,
            num :0
        }
    }
    backToTop = () => {
        this.props.scrollObj.scrollTo(0,0)
    }


    render() {
        const {isBack} = this.state
        const {backToTop,pos} = this       
        return (
            <i style={{
                display:isBack ? 'block' : 'none',
                right:pos.right,
                bottom:pos.bottom
                }} 
            className={styles.backTop} onClick={backToTop}></i>
        )
    }

    componentDidMount(){
        const {scrollObj} = this.props
        scrollObj.addEventListener('scroll',() => {
            const scrollTop = scrollObj==window ? (document.body.scrollTop || document.documentElement.scrollTop) : scrollObj.scrollTop

            this.setState({
                isBack: scrollTop > 400
            })            
        })

        if(scrollObj !== window){
            window.addEventListener('scroll',() =>{
                this.setState({
                    num : 0
                })
            })
            
        }
    }
}

export default BackTop
